<template>
  <view class="main">
    <view class="title-box">{{ themeName }}</view>
    <view class="bb_box">
      <image :src="picture" mode="widthFix" class="banner-img"></image>
      <view class="number_box">
        {{ wordList.length - noListenList.length }}/{{ planPerDayNum }}
      </view>
    </view>

    <view class="textBox">
      <!-- <text
        class="text"
        v-for="(item, index) in asList"
        :key="index"
        :class="
          currentTime > item.startSeconds && currentTime < item.endSeconds
            ? 'activeText'
            : ''
        "
        >{{ item.text }}</text
      > -->
      <view
        class="word_box"
        v-for="(item, index) in listenWordList"
        :key="index"
      >
        <text :class="currentLine == index + 1 ? 'activeText' : 'text'">{{
          item.content
        }}</text>
      </view>
    </view>
    <view class="bottom_box">
      <TnIcon
        name="server"
        size="30px"
        color="#BBBBBB"
        @tap="showWordListPopup"
      />
      <view class="btn-list">
        <image
          class="prev-btn"
          @click="handlePrev"
          src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/play/prev-btn.png"
        ></image>
        <view>
          <image
            class="play-btn"
            v-if="!isPlaying"
            @click="handleStart"
            src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/play/play-btn.png"
          >
          </image>
          <image
            class="play-btn"
            v-else
            @click="handlePause"
            src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/play/pause-btn.png"
          >
          </image>
        </view>
        <image
          class="next-btn"
          @click="handleNext"
          src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/play/next-btn.png"
        ></image>
      </view>
      <TnIcon name="set" size="30px" color="#BBBBBB" @tap="showSetting" />
    </view>
    <TnPopup v-model="showSettingPopup" open-direction="bottom">
      <view class="settingBox tn-p-lg">
        <view class="title"> 学习设置 </view>
        <view class="setting_main">
          <view class="setting_line">
            <view class="left_box"> 听中文 </view>
            <view class="right_box">
              <TnSwitch
                v-model="listenChinese"
                active-color="#5A7BF4"
                size="sm"
                @change="changeListenChinese"
              />
            </view>
          </view>
          <!-- <view class="setting_line">
            <view class="left_box"> 循环听 </view>
            <view class="right_box">
              <TnSwitch
                v-model="againListen"
                active-color="#5A7BF4"
                size="sm"
                @change="changeAgainListen"
              />
            </view>
          </view> -->
          <!-- <view class="setting_line">
            <view class="left_box"> 发音 </view>
            <view class="right_box">
              <TnRadioGroup v-model="speakPeople" @change="changeSpeak">
                <TnRadio label="0" active-color="#5A7BF4">男声</TnRadio>
                <TnRadio label="1" active-color="#5A7BF4">女声</TnRadio>
                <TnRadio label="2" active-color="#5A7BF4">儿声</TnRadio>
              </TnRadioGroup>
            </view>
          </view> -->
          <view class="setting_line">
            <view class="left_box"> 音频速度 </view>
            <view class="right_box">
              <TnRadioGroup v-model="speed" @change="changeSpeed">
                <TnRadio :label="1" active-color="#5A7BF4">2.0X</TnRadio>
                <TnRadio :label="2" active-color="#5A7BF4">1.5X</TnRadio>
                <TnRadio :label="3" active-color="#5A7BF4">1.0X</TnRadio>
                <TnRadio :label="4" active-color="#5A7BF4">0.8X</TnRadio>
              </TnRadioGroup>
            </view>
          </view>
          <view class="setting_line">
            <view class="left_box"> 播放顺序 </view>
            <view class="right_box">
              <TnRadioGroup v-model="order" @change="changeOrder">
                <TnRadio :label="1" active-color="#5A7BF4">顺序</TnRadio>
                <TnRadio :label="2" active-color="#5A7BF4">随机</TnRadio>
              </TnRadioGroup>
            </view>
          </view>
        </view>
      </view>
    </TnPopup>
    <TnPopup v-model="showListPopup" open-direction="bottom">
      <view class="listen_list_box tn-p-lg">
        <view class="title_line">
          <view class="title"> 今日听列表 </view>
          <view class="number_box">
            {{ wordList.length - noListenList.length }}/{{ planPerDayNum }}
          </view>
        </view>
        <view class="word_box">
          <view
            class="word_list"
            v-for="(item, index) in wordList"
            :key="index"
            @tap="toListenWord(index)"
          >
            <view class="word"> {{ item.content }} </view>
            <view class="chinese_word"> {{ item.translate }} </view>
            <view class="play_btn" v-if="listenIndex == index">
              <image
                src="../../static/images/play-css-blue.gif"
                mode="widthFix"
              />
            </view>
          </view>
        </view>
      </view>
    </TnPopup>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import {
  getDailyPlanApi,
  getSceneDetailById,
  toDown,
  toUp,
  updatePlanStatusApi,
  uploadSettingApi,
} from '@/services/api'
import { Base64 } from 'js-base64'
import { useWebsocket } from '@/hooks'
import srtParser2 from 'srt-parser-2'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import string from '@tuniao/tnui-vue3-uniapp/libs/async-validator/validator/string'
import TnSwitch from '@tuniao/tnui-vue3-uniapp/components/switch/src/switch.vue'
import { useUserStore } from '@/stores/modules/user'
const userStore = useUserStore()
const isPlaying = ref(false)
const showSettingPopup = ref(false)
const listenChinese = ref(true)
const repeatTimes = ref(0) //0不循环，-1反复循环
const speakPeople = ref()
const speed = ref()
const order = ref()
const showListPopup = ref(false)
const learnType = ref()
const scenseType = ref()
const planId = ref()
const bookId = ref()
const wordList = ref([] as any)
const listenWordList = ref([] as any)
const listenIndex = ref(0) // 当前播放单词的index
const currentLine = ref(0) //当前播放的行
const noListenList = ref([] as any) //未听单词的列表
const noListenIndex = ref([] as any) // 未听单词的index列表
const themeName = ref('')
const planPerDayNum = ref()
onLoad(async (options) => {
  listenChinese.value = userStore.getIfListenChinese == 1 ? true : false
  speakPeople.value = userStore.getSound_people
  speed.value = userStore.getSound_speed
  order.value = userStore.getSound_order
  learnType.value = options.learnType
  scenseType.value = options.scenseType
  planId.value = options.planId
  bookId.value = userStore.getBookId
  await getDailyPlan()
  getNoListenList()
  //随机播放
  if (order.value == 2) {
    setOrderListen()
    console.log('listenIndex.value ', listenIndex.value)
  } else {
    //顺序播放
    setNextListen()
  }
  setListenWord()
  handleStart()
  console.log(listenWordList.value)
})
// 获取未学习的列表
const getNoListenList = () => {
  noListenList.value = wordList.value.filter((item) => {
    return item.status != 1
  })
  console.log(noListenList.value, 'noListenList.value')
}
//设置随机播放
const setOrderListen = () => {
  console.log(noListenList.value, 'noListenList.value')
  //随机播放,通过控制listenIndex
  if (noListenList.value.length) {
    //还有未听的优先去遍历未听的列表
    //先获取未听列表的index,然后随机index
    noListenIndex.value = noListenList.value.map((item) => {
      return item.index
    })
    const index = Math.floor(Math.random() * noListenIndex.value.length)
    listenIndex.value = noListenIndex.value[index]
  } else {
    //没有未听的去遍历总列表
    const index = Math.floor(Math.random() * wordList.value.length)
    console.log('index历总列表', wordList.value.length)
    console.log('index历总列表', index)
    listenIndex.value = index
  }
}
//设置初始化的顺序播放的单词index
const setNextListen = () => {
  console.log(noListenList.value, 'noListenList.value')
  //随机播放,通过控制listenIndex
  if (noListenList.value.length) {
    //还有未听的优先去遍历未听的列表
    //先获取未听列表的index,然后随机index
    noListenIndex.value = noListenList.value.map((item) => {
      return item.index
    })
    // const index = Math.floor(Math.random() * noListenIndex.value.length)
    listenIndex.value = noListenIndex.value[0]
  } else {
    //没有未听的去遍历总列表
    // const index = Math.floor(Math.random() * wordList.value.length)
    // console.log('index历总列表', wordList.value.length)
    // console.log('index历总列表', index)
    listenIndex.value = 0
  }
}
//点击开始
const handleStart = () => {
  if (currentLine.value > 0) {
    promptSound.play()
    promptSound.onPlay(() => {
      isPlaying.value = true
    })
  } else {
    console.log(listenWordList.value)
    isPlaying.value = true
    // listenWordList.value.forEach((item) => {
    //   item.audioList[speakPeople.value - 1]
    // })
    currentLine.value = 1
    playSound()
  }
}
//暂停
const handlePause = () => {
  promptSound.pause()
  promptSound.onPause(() => {
    isPlaying.value = false
  })
}
const toListenWord = (index) => {
  console.log('点击切换')
  isPlaying.value = true
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  listenIndex.value = index
  currentLine.value = 1
  setListenWord()
  playSound()
}
//下一首
const handleNext = () => {
  console.log('下一首')
  isPlaying.value = true
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  if (order.value == 2) {
    //随机播放
    setOrderListen()
    currentLine.value = 1
    setListenWord()
    playSound()
  } else {
    if (listenIndex.value + 1 >= wordList.value.length) {
      //顺序播放已听完去全部
      listenIndex.value = 0
      currentLine.value = 1
      setListenWord()
      playSound()
    } else {
      listenIndex.value += 1
      currentLine.value = 1
      setListenWord()
      playSound()
    }
  }
}
//上一首
const handlePrev = () => {
  console.log('上一首')
  isPlaying.value = true
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  if (order.value == 2) {
    //随机播放
    setOrderListen()
    currentLine.value = 1
    setListenWord()
    playSound()
  } else {
    if (listenIndex.value - 1 < 0) {
      //顺序播放已听完去全部
      listenIndex.value = wordList.value.length - 1
      currentLine.value = 1
      setListenWord()
      playSound()
    } else {
      listenIndex.value -= 1
      currentLine.value = 1
      setListenWord()
      playSound()
    }
  }
}
onHide(() => {
  console.log('onHide')
  // promptSound.stop()
  // currentLine.value = 1
})
const stopListen = ref(false)
onUnload(() => {
  console.log('onUnload')
  stopListen.value = true
  promptSound.stop()
  currentLine.value = 1
})
var promptSound = null
//播放MP3
const playSound = async () => {
  if (!stopListen.value) {
    // promptSound = uni.getBackgroundAudioManager()
    promptSound = uni.createInnerAudioContext()

    // promptSound.obeyMuteSwitch = false
    // wx.setInnerAudioOption({ obeyMuteSwitch: false })
    if (currentLine.value <= listenWordList.value.length) {
      let src =
        listenWordList.value[currentLine.value - 1].audioList[
          speakPeople.value - 1
        ].audioUrl
      // let src =
      //   listenWordList.value[currentLine.value - 1].audioList[
      //     speakPeople.value - 1
      //   ].audioUrl +
      //   '?t=' +
      //   new Date().getTime()

      // promptSound.title = listenWordList.value[currentLine.value - 1].content
      // promptSound.singer = '暂无'
      // promptSound.coverImgUrl =
      //   listenWordList.value[currentLine.value - 1].lessonUrl
      // Split the URL into parts
      const urlParts = src.split('/')
      // Find the index of the part containing Chinese characters
      const chinesePartIndex = urlParts.findIndex((part) =>
        /[\u4e00-\u9fa5]/.test(part)
      )

      // Encode the part containing Chinese characters
      if (chinesePartIndex !== -1) {
        urlParts[chinesePartIndex] = encodeURIComponent(
          urlParts[chinesePartIndex]
        )
      }

      // Reconstruct the URL
      const encodedSrc = urlParts.join('/')
      promptSound.src = encodedSrc
      //设置mp3播放速度
      promptSound.playbackRate =
        speed.value == 1
          ? 2.0
          : speed.value == 2
            ? 1.5
            : speed.value == 3
              ? 1.0
              : speed.value == 4
                ? 0.8
                : 1.0
      console.log(src, 'src')
      console.log(encodedSrc, 'encodedSrc')
      console.log('开始播放')
      promptSound.play() //执行播放
      promptSound.onEnded(() => {
        promptSound.stop()
        // promptSound.destroy()
        console.log('播放结束')
        currentLine.value += 1
        playSound()
      })
      promptSound.onError((e) => {
        console.log('播放错误', e)
      })
      // promptSound.onPause(() => {
      //   handlePause()
      // })
      // promptSound.onPrev(() => {
      //   handlePrev()
      // })
      // promptSound.onNext(() => {
      //   handleNext()
      // })
    } else {
      //repeatTimes=0则本单词不循环，-1为一直循环
      if (repeatTimes.value == 0) {
        await noAgainListen()
      }
      if (repeatTimes.value == -1) {
        await againListen()
      }
      if (repeatTimes.value > 0) {
        //循环次数
        await againNumberListen()
      }
    }
  }
}
const ifReadEnd = ref(false)
watch(
  () => noListenList.value,
  async (newVal, oldVal) => {
    console.log('noListenList.value', oldVal, newVal)
    //第一次读完任务就弹出来
    if (oldVal.length != 0 && newVal.length == 0) {
      console.log('77777777777777777777')
      ifReadEnd.value = true
      // isPlaying.value = false
      // if (promptSound) {
      //   console.log('播放中停止播放')
      //   promptSound.stop()
      //   promptSound = null
      // }
      // uni.showModal({
      //   content: `恭喜您已完成计划`,
      //   confirmText: '继续听吧',
      //   cancelText: '休息一下',
      //   success: function (res) {
      //     if (res.confirm) {
      //       console.log('制定计划重新学')
      //       uni.navigateTo({
      //         url: `/home-page/setPlan/index?data=${encodeURIComponent(JSON.stringify(planDetail.value))}&ifFinish=${0}`,
      //       })
      //     } else if (res.cancel) {
      //       console.log('知道了')
      //     }
      //   },
      // })
    }
  }
)
const isReadFinish = () => {
  ifReadEnd.value = false
  isPlaying.value = false
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  uni.showModal({
    content: `恭喜您已完成计划`,
    confirmText: '继续听吧',
    cancelText: '休息一下',
    success: function (res) {
      if (res.confirm) {
        console.log('制定计划重新学')
        //随机播放
        if (order.value == 2) {
          setOrderListen()
          console.log('listenIndex.value ', listenIndex.value)
        } else {
          //顺序播放
          if (listenIndex.value + 1 >= wordList.value.length) {
            listenIndex.value = 0
          } else {
            listenIndex.value += 1
          }
        }
        isPlaying.value = true
        currentLine.value = 1
        setListenWord()
        playSound()
      } else if (res.cancel) {
        uni.switchTab({
          url: '/pages/index/index',
        })
        console.log('知道了')
      }
    },
  })
}
var againNumber = 0
//不循环
const noAgainListen = async () => {
  //当前单词听完请求接口保存记录
  const params = {
    bookId: userStore.getBookId,
    learnType: Number(learnType.value),
    lessonId: wordList.value[listenIndex.value].lessonId,
    status: 1,
  }
  const data = await updatePlanStatusApi(params)
  if (data.code === 200) {
    noListenList.value = noListenList.value.filter((item) => {
      return item.lessonId != wordList.value[listenIndex.value].lessonId
    })
    console.log(noListenList.value, 'noListenList.value88888888')
    // setOrderListen()
    //已经听完计划
    setTimeout(() => {
      if (ifReadEnd.value) {
        isReadFinish()
      } else {
        console.log('77777777777777777777')
        if (order.value == 2) {
          //随机播放
          setOrderListen()
          currentLine.value = 1
          setListenWord()
          playSound()
        } else {
          if (listenIndex.value + 1 >= wordList.value.length) {
            //顺序播放已听完去全部
            listenIndex.value = 0
            currentLine.value = 1
            setListenWord()
            playSound()
          } else {
            listenIndex.value += 1
            currentLine.value = 1
            setListenWord()
            playSound()
          }
        }
      }
    }, 0)
  }
}
//一直循环
const againListen = async () => {
  //当前单词听完请求接口保存记录
  const params = {
    bookId: userStore.getBookId,
    learnType: Number(learnType.value),
    lessonId: wordList.value[listenIndex.value].lessonId,
    status: 1,
  }
  const data = await updatePlanStatusApi(params)
  if (data.code === 200) {
    noListenList.value = noListenList.value.filter((item) => {
      return item.lessonId != wordList.value[listenIndex.value].lessonId
    })
    console.log(noListenList.value, 'noListenList.value88888888')
    //已经听完计划
    setTimeout(() => {
      if (ifReadEnd.value) {
        isReadFinish()
      } else {
        currentLine.value = 1
        setListenWord()
        playSound()
      }
    }, 0)
  }
}

//循环次数
const againNumberListen = async () => {
  if (againNumber < repeatTimes.value) {
    //当前单词听完请求接口保存记录
    //循环最后一遍请求接口
    if (againNumber + 1 == repeatTimes.value) {
      const params = {
        bookId: userStore.getBookId,
        learnType: Number(learnType.value),
        lessonId: wordList.value[listenIndex.value].lessonId,
        status: 1,
      }
      const data = await updatePlanStatusApi(params)
      if (data.code === 200) {
        noListenList.value = noListenList.value.filter((item) => {
          return item.lessonId != wordList.value[listenIndex.value].lessonId
        })
        console.log(noListenList.value, 'noListenList.value88888888')

        currentLine.value = 1
        againNumber += 1
        setListenWord()
        playSound()
      }
    } else {
      currentLine.value = 1
      againNumber += 1
      setListenWord()
      playSound()
    }
  } else {
    againNumber = 0
    //已经听完计划
    setTimeout(() => {
      if (ifReadEnd.value) {
        isReadFinish()
      } else {
        if (order.value == 2) {
          console.log('循环结束')
          //随机播放
          setOrderListen()
          console.log(listenIndex.value, 'listenIndex.value循环结束')
          currentLine.value = 1
          setListenWord()
          console.log(listenWordList.value, 'listenWordList.value循环结束')
          playSound()
        } else {
          if (listenIndex.value + 1 >= wordList.value.length) {
            //顺序播放已听完去全部
            listenIndex.value = 0
            currentLine.value = 1
            setListenWord()
            playSound()
          } else {
            listenIndex.value += 1
            currentLine.value = 1
            setListenWord()
            playSound()
          }
        }
      }
    }, 0)
  }
}
const getDailyPlan = async () => {
  const params = {
    // bookId: bookId.value,
    bookId: userStore.getBookId,
    planId: planId.value,
    scenseType: scenseType.value,
    learnType: learnType.value,
  }
  const data = await getDailyPlanApi(params)
  if (data.code == 200) {
    wordList.value = data.data.bookLessonList
    repeatTimes.value = data.data.repeatTimes
    planPerDayNum.value = data.data.planPerDayNum
    wordList.value.forEach((item, index) => {
      item.index = index
    })
  }
  // wordList.value = [
  //   {
  //     lessonId: 1,
  //     lessonUrl: '',
  //     pronounce: '/sku:I/',
  //     content: 'school',
  //     translate: '学校',
  //     translateAudioList: [
  //       {
  //         type: 1,
  //         audioUrl:
  //           'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/nice.mp3',
  //       },
  //       {
  //         type: 2,
  //         audioUrl: 'xxx2.url',
  //       },
  //       {
  //         type: 3,
  //         audioUrl: 'xxx3.url',
  //       },
  //     ],
  //     audioList: [
  //       {
  //         type: 1,
  //         audioUrl:
  //           'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/over.mp3',
  //       },
  //       {
  //         type: 2,
  //         audioUrl: 'xxx2.url',
  //       },
  //       {
  //         type: 3,
  //         audioUrl: 'xxx3.url',
  //       },
  //     ],
  //     userAudioUrl: '',
  //     status: 2,
  //     extendContentList: [
  //       {
  //         contentId: 1,
  //         content: 'Do you want to see my hometown',
  //         audioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //         ],
  //         translate: '你想去看看我的家乡吗？',
  //         translateAudioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //           {
  //             type: 0,
  //             audioUrl: '222.url',
  //           },
  //         ],
  //         name: 'example',
  //         userAudioUrl: '',
  //         userAudioContent: '',
  //       },
  //       {
  //         contentId: 1,
  //         content: 'Do you want to see my hometown',
  //         audioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //         ],
  //         translate: '你想去看看我的家乡吗1111？',
  //         translateAudioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //           {
  //             type: 0,
  //             audioUrl: '222.url',
  //           },
  //         ],
  //         name: 'example',
  //         userAudioUrl: '',
  //         userAudioContent: '',
  //       },
  //       {
  //         contentId: 1,
  //         content: 'Do you want to see my hometown',
  //         audioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //         ],
  //         translate: '你想去看看我的家乡吗222？',
  //         translateAudioList: [
  //           {
  //             type: 0,
  //             audioUrl: '111.url',
  //           },
  //           {
  //             type: 0,
  //             audioUrl: '222.url',
  //           },
  //         ],
  //         name: 'example',
  //         userAudioUrl: '',
  //         userAudioContent: '',
  //       },
  //     ],
  //   },
  // ]
}
const setListenWord = () => {
  console.log(learnType.value)
  let wordObjectList = [] //单词列表
  let sentenceList = [] //句子列表
  if (learnType.value == 1 || learnType.value == 3) {
    console.log(listenIndex.value, 'listenIndex.value')
    const object = wordList.value[listenIndex.value]
    console.log(wordList.value, 'wordList.value')
    console.log(object, 'object')
    //如果听翻译
    if (listenChinese.value) {
      const translateObject = {
        content: object.translate,
        audioList: object.translateAudioList,
      } //翻译的对象
      listenWordList.value = [object, translateObject]
    } else {
      listenWordList.value = [object]
    }
    wordObjectList = listenWordList.value
  }
  if (learnType.value == 2 || learnType.value == 3) {
    console.log('hhhhhhhhhhhhh', wordList.value[listenIndex.value])
    const array = wordList.value[listenIndex.value].extendContentList
    array[0].lessonUrl = wordList.value[listenIndex.value].lessonUrl
    array[0].themeName = wordList.value[listenIndex.value].themeName
    console.log(array, 'array')
    //如果听翻译
    if (listenChinese.value) {
      const array2 = []
      array.forEach((item, index) => {
        if (item.translate != '') {
          const translateObject = {
            content: item.translate,
            audioList: item.translateAudioList,
          } //翻译的对象
          array2.push(item, translateObject)
        } else {
          array2.push(item)
        }
        console.log(array2, 'array2')
        // array.splice(index + 1, 0, translateObject)
      })
      listenWordList.value = [...array2]
    } else {
      listenWordList.value = [...array]
    }
    sentenceList = listenWordList.value
  }
  if (learnType.value == 3) {
    listenWordList.value = [...wordObjectList, ...sentenceList]
  }
  console.log(listenWordList.value, 'kkkkkkkkkkkkkkkkkk')
  themeName.value = listenWordList.value[0].themeName
  picture.value = listenWordList.value[0].lessonUrl
  console.log('picture.value', picture.value)
}
const showSetting = () => {
  showSettingPopup.value = true
}
const showWordListPopup = () => {
  showListPopup.value = true
}
const changeListenChinese = async () => {
  const data = await uploadSettingApi({
    listenChineseStatus: listenChinese.value == true ? 1 : 2,
  })
  if (data.code === 200) {
    userStore.setListenChinese(listenChinese.value)
    isPlaying.value = true
    if (promptSound) {
      console.log('播放中停止播放')
      promptSound.stop()
      promptSound = null
    }
    listenIndex.value = listenIndex.value
    currentLine.value = 1
    setListenWord()
    playSound()
    //听中文
    // if (userStore.getIfListenChinese == 1) {
    //   listenIndex.value = listenIndex.value
    //   currentLine.value = currentLine.value * 2
    //   setListenWord()
    // } else {
    //   //不听中文
    //   listenIndex.value = listenIndex.value
    //   currentLine.value = Math.ceil(currentLine.value / 2) + 1
    //   setListenWord()
    // }
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    listenChinese.value = !listenChinese.value
  }
}
const changeSpeed = async () => {
  const data = await uploadSettingApi({
    playSpeed: speed.value,
  })
  if (data.code === 200) {
    userStore.setSoundSpeed(speed.value)
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    speed.value = userStore.getSound_speed
  }
}
const changeOrder = async () => {
  const data = await uploadSettingApi({
    playOrder: order.value,
  })
  if (data.code === 200) {
    userStore.setOrder(order.value)
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    order.value = userStore.getSound_order
  }
}

var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()
const {
  connectWebSocketComment,
  connectWebSocket,
  APPID,
  toBase64,
  handlePlayVideo,
  textTranslate,
  webSocketSendComment,
  webSocketSend,
  base64toJson,
  handleClickVideo,
  webSocketSendMp3,
  handleCloseVideo,
  splitText,
  closeWebSocket,
} = useWebsocket()
const innerAudioContext = uni.createInnerAudioContext()
const answer = ref('')
const audioSrc = ref('')
const titleName = ref('')
const answerList = ref([] as any)
const activeWord = ref()
const answering = ref(false)
const currentTime = ref(0)
const picture = ref('')
const asList = ref([
  { text: '一日三餐的对话', startSeconds: 0, endSeconds: 0 },
  { text: 'fish', startSeconds: 0, endSeconds: 0 },
  { text: '鱼肉；鱼', startSeconds: 0, endSeconds: 0 },
  { text: 'Id like some fish and rice', startSeconds: 0, endSeconds: 0 },
  { text: '我想吃些鱼肉和米饭。', startSeconds: 0, endSeconds: 0 },
] as any)
const audio = ref('')
const playing = ref(false)
let music = uni.createInnerAudioContext()
// let promptSound = uni.createInnerAudioContext() //提示音
const overMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/over.mp3'
const niceMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/nice.mp3'
const excellent =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/excellent.mp3'
// music.src =
//   'https://api.chongli.maiyajia.com/uploads/01_hello_lesson1_4980ad0a58.MP3'
const activeTap = ref(0) //0为AI朗读，1为智能跟读
const readLine = ref(-1) //当前需要朗读的第几行
// const showtipPopup = ref(true)
const progressPercent = ref(100) //进度条百分比
const ifReading = ref(false) //是否朗读中
const duration = ref(0) //当前句子的时长
const currentItem = ref({} as any) //当前朗读的句子
const tempFilePath = ref() //录音文件
const readList = ref([] as any) //跟读句子列表
const isAnimation = ref(false)
// 获取录音
const recorderManager = uni.getRecorderManager()
const ids = ref([]) //读过的文章id
const styleId = ref('')
const ifZanStatus = ref(0) //0初始值，1赞,2踩
const asDetail = ref({} as any) //文章详情
const changeTap = (index: number) => {
  if (activeTap.value == 0 && index == 0) {
    console.log('开始播放')
    onPlayIconClick()
  } else {
    music.stop()
    playing.value = false
  }
  activeTap.value = index
}
const toListing = () => {
  if (activeTap.value == 0) {
    console.log('开始播放和暂停')
    onPlayIconClick()
  } else {
    activeTap.value = 0
  }
}
const toReading = () => {
  music.stop()
  playing.value = false
  readList.value = JSON.parse(JSON.stringify(asList.value))
  console.log('智能跟读', readList.value)
  //刷新
  refresh()
  activeTap.value = 1
}

watch(
  () => activeTap.value,
  (newProps) => {
    console.log(newProps)
    if (newProps == 1) {
      // 智能跟读模块的初始化
      uni.showModal({
        title: '提示',
        content: '请在规定时间内朗读下面的句子',
        success: function (res) {
          if (res.confirm) {
            console.log('立即朗读')
            readLine.value = 0
            readSentence()
          } else if (res.cancel) {
            console.log('先不朗读')
          }
        },
      })
      // showtipPopup.value = true
    }
  }
)
//朗读倒计时
const readSentence = () => {
  if (readLine.value > readList.value.length - 1) {
    // 朗读结束刷新
    refresh()
    return false
  } else {
    console.log('33333', readList.value)
    //当前需要朗读的第几行
    ifReading.value = true
    currentItem.value = readList.value[readLine.value]
    duration.value =
      (currentItem.value.endSeconds - currentItem.value.startSeconds) * 1000 +
      3000
    //打开websoket
    startRecord()
    setTimeout(() => {
      endRecord()
    }, duration.value)
  }
}

// 朗读开始录制
const startRecord = () => {
  try {
    console.log(
      'sdhcdbcdjncdkmckl/dmfm l.mk/md;.',
      readList.value[readLine.value]
    )
    connectWebSocket().then((res) => {
      if (res != '') {
        console.log(
          '识别到文字成功返回识别到文字成功返回识别到文字成功返回',
          res
        )
        readList.value[readLine.value].result = res
        readList.value[readLine.value].isShowResult = true
      } else {
        console.log('3333', res)
        readList.value[readLine.value].isShowResult = false
        uni.showToast({
          title: '未识别到文字',
          icon: 'none',
        })
      }
    })
    // 评分
    connectWebSocketComment(readList.value[readLine.value].text)
      .then((res) => {
        console.log('4444', res)
        readList.value[readLine.value].isShowComment = true
        readList.value[readLine.value].rateValue = Number(res.total_score)
        if (!readList.value[readLine.value].hasOwnProperty('repeatNum')) {
          readList.value[readLine.value].repeatNum = 0
        }
        console.log('成功评分结果', readList.value[readLine.value])
        //打分成功且分数大于三分则继续朗读下一句
        if (
          readList.value[readLine.value].rateValue < 3 &&
          readList.value[readLine.value].repeatNum < 1
        ) {
          uni.showToast({
            title: '不合格再读一遍吧',
            icon: 'none',
            duration: 2000,
          })
          playSound(readList.value[readLine.value].rateValue).then(() => {
            console.log('444播放结束')
            let currentIndex = readLine.value
            readLine.value = -1
            setTimeout(() => {
              console.log('777播放结束')
              readLine.value = currentIndex
              readList.value[readLine.value].repeatNum += 1
              readSentence()
              console.log('888播放结束')
            }, 2000)
          })
          // //播放提示音
          // playSound(readList.value[readLine.value].rateValue)
          // //监听提示音播放结束
          // promptSound.onEnded(() => {
          //   console.log('333播放结束')
          //   promptSound.stop()
          //   promptSound.destroy()
          //   console.log('444播放结束')
          //   let currentIndex = readLine.value
          //   readLine.value = -1
          //   setTimeout(() => {
          //     console.log('777播放结束')
          //     readLine.value = currentIndex
          //     readList.value[readLine.value].repeatNum += 1
          //     readSentence()
          //     console.log('888播放结束')
          //   }, 2000)
          // })
        } else {
          // //播放提示音
          // playSound(readList.value[readLine.value].rateValue)
          // //监听提示音播放结束
          // promptSound.onEnded(() => {
          //   console.log('555播放结束')
          //   promptSound.stop()
          //   promptSound.destroy()
          //   readLine.value += 1
          //   readSentence()
          //   console.log('666播放结束')
          // })
          if (
            readList.value[readLine.value].repeatNum >= 1 &&
            readList.value[readLine.value].rateValue < 3
          ) {
            readLine.value += 1
            readSentence()
          } else {
            playSound(readList.value[readLine.value].rateValue).then(() => {
              readLine.value += 1
              readSentence()
              console.log('666播放结束')
            })
          }
        }
      })
      .catch((err) => {
        console.log('成功失败结果', err)
        readList.value[readLine.value].isShowComment = false
        readList.value[readLine.value].rateValue = 0
        console.log(readList.value[readLine.value])
        uni.showToast({
          title: '识别失败请再读一遍',
          icon: 'none',
          duration: 2000,
        })
        //播放提示音
        // playSound(readList.value[readLine.value].rateValue)
        // //监听提示音播放结束
        // promptSound.onEnded(() => {
        //   console.log('333播放结束')
        //   promptSound.stop()
        //   promptSound.destroy()
        //   let currentIndex = readLine.value
        //   readLine.value = -1
        //   setTimeout(() => {
        //     readLine.value = currentIndex
        //     readSentence()
        //   }, 2000)
        // })
        playSound(readList.value[readLine.value].rateValue).then(() => {
          let currentIndex = readLine.value
          readLine.value = -1
          setTimeout(() => {
            readLine.value = currentIndex
            readSentence()
          }, 2000)
        })
      })
    recorderManager.start({
      duration: 30000, // 600000（10 分钟）,默认值 60000（1 分钟）
      numberOfChannels: 1, // 录音通道数，有效值 1/2
      frameSize: 1,
      format: 'pcm', // 音频格式
      sampleRate: 16000, // 采样率
    })
    console.log('7777')
  } catch (e) {
    console.log('错误了', e)
  }

  // state.list[currentIndex.value].isShowResult = true
  // 常规
}

// 朗读停止
const endRecord = () => {
  console.log(
    '朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束'
  )
  // state.currentItem = item
  // currentIndex.value = index
  recorderManager.stop()
  ifReading.value = false
  // animation.value = false
}
const startWatch = () => {
  var lastFrame = [] as any
  recorderManager.onStop(function (res) {
    console.log('6666', lastFrame)
    // 监听最后一帧
    // 基础
    webSocketSend(lastFrame, true).then((res) => {
      if (res == 'success') {
      }
    })
    webSocketSendComment(
      lastFrame,
      readList.value[readLine.value].text,
      true
    ).then((res) => {
      if (res == 'success') {
      }
    })

    console.log('8888', res)
    let tempFile = res.tempFilePath //音频文件地址
    tempFilePath.value = tempFile
    // #ifdef MP-WEIXIN
    const fs = uni.getFileSystemManager()
    // 评分
    fs.readFile({
      //读取文件并转为ArrayBuffer
      filePath: tempFile,
      success(res) {},
    })
    // #endif
  })
  recorderManager.onFrameRecorded(function (res) {
    console.log('9999', res)
    const { frameBuffer, isLastFrame } = res
    lastFrame = frameBuffer
    let newFrameBuffer = Array.from(new Uint8Array(frameBuffer))
    // 基础
    webSocketSend(frameBuffer, isLastFrame).then((res) => {
      if (res == 'success') {
      }
    })
    // 评分
    webSocketSendComment(
      frameBuffer,
      readList.value[readLine.value].text,
      isLastFrame
    ).then((res) => {
      if (res == 'success') {
      }
    })
  })
}
//刷新智能跟读
const refresh = () => {
  readLine.value = -1
  ifReading.value = false
  duration.value = 0
  currentItem.value = {}
}
//换一批
const toChangeNew = () => {
  isAnimation.value = true
  getData()
}

const onPlayIconClick = () => {
  if (playing.value) {
    music.pause()
    playing.value = false
  } else {
    music.play() //执行播放
    music.onPlay(() => {
      console.log('开始播放')
      playing.value = true
    })
    music.onTimeUpdate(() => {
      currentTime.value = music.currentTime
      console.log(currentTime.value)
    })
    music.onEnded(() => {
      //播放结束
      music.stop()
      playing.value = false
      console.log('播放结束')
    })
  }
}

const str = ref('')
var parser = new srtParser2()

const animation = () => {
  console.log('animation结束')
  isAnimation.value = false
}
//将'00:01:60,888'格式时间转化为秒
const setTime = (time) => {
  let aTime = time.split(',')[0]
  let sTime = '.' + time.split(',')[1]
  let s = aTime.split(':')[0]
  let f = aTime.split(':')[1]
  let m = aTime.split(':')[2]
  let allTime = Number(s * 3600 + f * 60 + Number(m) + sTime)
  return allTime
}
const getData = () => {
  let params = { ids: ids.value }
  getSceneDetailById(styleId.value, params).then((res) => {
    const { code, data } = res
    if (code === 0) {
      if (data.id !== 0) {
        console.log('data', data)
        // // answer.value = Base64.decode(data.content) //Base64解密
        // answer.value = data.content
        // // answer.value.replace(/[\n\r]/g, '<br>')
        // answerList.value = answer.value.split(/\n/)
        asDetail.value = data
        str.value = data.subtitles
        asList.value = parser.fromSrt(str.value)
        ids.value.push(data.id)
        console.log('uuuuu', asList.value)
        music.src = data.audio
        audio.value = data.audio
        picture.value = data.picture
        ifZanStatus.value = data.like
        readList.value = JSON.parse(JSON.stringify(asList.value))
      } else {
        uni.showToast({
          title: '暂时没有更多咯!',
          icon: 'none',
          duration: 2000,
        })
      }
    }
    setTimeout(() => {
      isAnimation.value = false
    }, 2000)
  })
}

//点赞
const onZanIconClick = async () => {
  const res = await toUp(asDetail.value.id)
  if (res.code === 0) {
    if (res.status === 1) {
      ifZanStatus.value = 1
      uni.showToast({
        title: '已赞',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}
// 点踩
const onCaiIconClick = async () => {
  const res = await toDown(asDetail.value.id)
  if (res.code === 0) {
    if (res.status === 2) {
      ifZanStatus.value = 2
      uni.showToast({
        title: '已踩',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}
//提示音播放
// const playSound = (score) => {
//   return new Promise((resolve, reject) => {
//     let sound =
//       score < 3
//         ? overMp3
//         : 3 <= score && score < 4
//           ? niceMp3
//           : score >= 4
//             ? excellent
//             : ''
//     promptSound.src = sound
//     promptSound.play() //执行播放
//     console.log('开始播放')
//     promptSound.onEnded(() => {
//       promptSound.stop()
//       console.log('播放结束')
//       resolve(true)
//     })
//     // promptSound.onPlay(() => {
//     //   console.log('开始播放')
//     // })
//     promptSound.onError((res) => {
//       console.log(res.errMsg)
//     })
//   })
// }

const jumpBreakAnswerPage = () => {
  let encoded = Base64.btoa(
    unescape(encodeURIComponent(JSON.stringify(asList.value)))
  )
  tnNavPage(
    `/home-page/agent/break-answer?answerEn=${encoded}&source=2&audio=${audio.value}`
  )
}

//中文翻译成英文
const onTranslate = (answerZh) => {
  plugin.translate({
    lfrom: 'zh_CN',
    lto: 'en_US',
    content: answerZh,
    success: function (res) {
      if (res.retcode == 0) {
        answer.value = res.result
        outputText(answer.value)
      } else {
        console.warn('翻译失败', res)
      }
    },
    fail: function (res) {
      console.log('网络失败', res)
    },
  })
}

//流式输出文字
const outputText = (text) => {
  var index = 0
  const streamOutput = () => {
    if (index < text.length) {
      var currentText = text.substring(0, index + 1)
      answer.value = currentText
      index++
    } else {
      clearInterval(timer)
    }
  }
  let timer = setInterval(streamOutput, 20)
}

//英文转语音
// const textToSpeech = () => {
//   return new Promise((resolve, reject) => {
//     plugin.textToSpeech({
//       lang: 'en_US',
//       tts: true,
//       content:
//         answer.value.length < 900 ? answer.value : answer.value.slice(0, 900),
//       success: function (res) {
//         console.log('succ tts', res.filename)
//         audioSrc.value = res.filename
//         resolve()
//       },
//       fail: function (res) {
//         console.log('fail tts', res)
//       },
//     })
//   })
// }

const stopAudio = () => {
  innerAudioContext.stop()
}

//讯飞的语音播放接口
// const onPlayIconClick = async () => {
//   // Chinese中文 | English英文
//   answerList.value = answer.value.split(/\n/)
//   console.log(answerList.value)
//   playAudio(0)
// }
//利用递归函数去遍历每一句话的播放
// const playAudio = async (sum: number) => {
//   try {
//     let answerIndex = sum
//     if (answerIndex < answerList.value.length) {
//       // 发送消息获取音频并处理
//       const res = await webSocketSendMp3(
//         answerList.value[answerIndex],
//         'English'
//       )
//       let audioDataArray = [] as any
//       res.forEach((item, index) => {
//         const arrayBuffer = wx.base64ToArrayBuffer(item)
//         const newBuffer = new Uint8Array(arrayBuffer)
//         audioDataArray.push(...newBuffer)
//       })
//       const uint8Array = new Uint8Array(audioDataArray)
//       const audioUrl = wx.createBufferURL(uint8Array.buffer)

//       // 播放音频并处理播放状态,播放该句子就会高亮，该句子的索引
//       activeWord.value = answerIndex
//       answering.value = true
//       await handlePlayVideo(audioUrl)

//       // 继续播放下一句
//       await playAudio(answerIndex + 1)
//     } else {
//       answering.value = false
//     }
//   } catch (error) {
//     console.error('播放音频时出错：', error)
//     // 可以添加错误处理逻辑，比如重试播放或提醒用户
//   }
// }
const onCopyIconClick = () => {
  uni.setClipboardData({
    data: answer.value,
    success: function () {},
  })
}
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  min-height: 100vh;
  padding: 32rpx;
  background: #e0ffe2;
  .title-box {
    width: 100%;
    height: 68rpx;
    line-height: 68rpx;
    text-align: center;
    background: linear-gradient(225deg, #f9ffab 4%, #69bf6e 90%);
    color: #fff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
  }
  .bb_box {
    width: 100%;
    position: relative;
    .banner-img {
      width: 100%;
      // height: 384rpx;
      margin-bottom: 24rpx;
    }
    .number_box {
      position: absolute;
      left: 10rpx;
      top: 10rpx;
      color: #fff;
    }
  }
  .textBox {
    width: 100%;
    .word_box {
      .text {
        width: 100%;
        display: block;
        line-height: 64rpx;
        font-size: 32rpx;
        color: #000000;
        border-radius: 22rpx;
        margin-bottom: 20rpx;
        background-color: #ffffff;
        padding: 10rpx 30rpx;
        box-sizing: border-box;
        font-weight: bold;
      }
      .activeText {
        width: 100%;
        display: block;
        line-height: 64rpx;
        border-radius: 22rpx;
        margin-bottom: 20rpx;
        background-color: #ffffff;
        padding: 10rpx 30rpx;
        box-sizing: border-box;
        color: #4b49e8;
        font-size: 40rpx;
        font-weight: bold;
      }
    }
    .result-wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 100%;
      .comment-box {
        max-width: 500rpx;
        background: #fff;
        display: flex;
        align-items: flex-end;
        padding: 20rpx;
        border-radius: 40rpx;
        flex-direction: column;
      }
      image {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
      }
    }
  }
  .bottom_box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 200rpx;
    background: #fff;
    display: flex;
    justify-content: space-between;
    padding: 0 32rpx;
    .btn-list {
      // width: 100%;
      height: 100%;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 144rpx;

      image {
        width: 50rpx;
        height: 50rpx;
      }

      .play-btn {
        width: 110rpx;
        height: 110rpx;
      }
    }
  }
  .settingBox {
    .title {
      width: 100%;
      text-align: center;
    }
    .setting_main {
      margin-top: 20rpx;
      .setting_line {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;
        .left_box {
          font-size: 28rpx;
          color: #101010;
          font-weight: bold;
        }
        .right_box {
        }
      }
    }
  }
  .listen_list_box {
    .title_line {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      .title {
        font-size: 36rpx;
        color: #101010;
        font-weight: bold;
      }
      .number_box {
        font-size: 32rpx;
        color: #6c6c6c;
      }
    }
    .word_box {
      width: 100%;
      height: 500rpx;
      overflow-y: scroll;
      .word_list {
        height: 80rpx;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #e0e0e0;
        padding: 0 20rpx;
        .word {
          width: 250rpx;
          font-size: 32rpx;
          color: #333333;
          font-weight: bold;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .chinese_word {
          width: 250rpx;
          font-size: 28rpx;
          color: #6c6c6c;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin: 0 20rpx;
        }
        .play_btn {
          width: 50rpx;
          height: 50rpx;
          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
